<template>
  <div class="role">
    <top-title
      title="账号管理"
      btn-text="添加账号"
      @add="handleAdd"
    />
    <n-flex class="box">
      <custom-table-filter />
      <n-data-table
        :columns="columns"
        :data="list"
        style="height: calc(100vh - 300px)"
      />
      <custom-pagination
        v-model:total="total"
        v-model:page-num="pageNum"
        v-model:page-size="pageSize"
      />
    </n-flex>
    <custom-form
      v-model:visible="visible"
      v-model:form="form"
      :config-list="configList"
      :width="540"
      :height="600"
      @confirm="handleConfirm"
      @cancel="handleClose"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h } from 'vue'
  import { NButton, NFlex } from 'naive-ui'
  import type { DataTableColumns } from 'naive-ui'
  // 表头
  const columns = ref<DataTableColumns<Required<User>>>([
    {
      title: '昵称',
      key: 'nickName'
    },
    {
      title: '账号',
      key: 'username'
    },
    {
      title: '手机号码',
      key: 'phoneNumber'
    },
    {
      title: '操作',
      key: 'operate',
      width: 200,
      align: 'center',
      render(row) {
        return h(
          NFlex,
          {
            justify: 'center'
          },
          {
            default: () => [
              h(
                NButton,
                {
                  size: 'small',
                  text: true,
                  type: 'primary',
                  onClick: () => handleEdit(row.id)
                },
                { default: () => '编辑' }
              ),
              h(
                NButton,
                {
                  size: 'small',
                  text: true,
                  type: 'error',
                  onClick: () => handleDel(row.id)
                },
                { default: () => '删除' }
              )
            ]
          }
        )
      }
    }
  ])
  // 弹窗
  const visible = ref(false)

  // 表单数据
  const form = ref<any>({
    username: '',
    password: '',
    status: 1,
    nickName: '',
    roleIds: []
  })
  // 表单配置
  const basicConfigList = ref<FormRenderConfig[]>([
    {
      type: 'input',
      label: '昵称',
      key: 'nickName',
      span: 24
    },
    {
      type: 'input',
      label: '账号',
      key: 'username',
      span: 24
    },
    {
      type: 'input',
      label: '密码',
      key: 'password',
      span: 24
    },
    {
      type: 'radio',
      label: '状态',
      key: 'status',
      span: 24,
      options: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 }
      ]
    },
    {
      type: 'input',
      label: '手机号码',
      key: 'phoneNumber',
      span: 24
    },
    {
      type: 'checkbox',
      label: '角色',
      key: 'roleIds',
      span: 24,
      options: []
    }
  ])
  // 0:新增 1：编辑
  const configType = ref<0 | 1>(0)

  const configList = computed(() => {
    if (configType.value === 0) return basicConfigList.value
    return basicConfigList.value
      .filter(item => item.key !== 'password')
      .map(item => {
        item.span = 24
        return item
      })
  })
  // 获取角色列表
  function getRoleList() {
    http.get('admin/role/all').then(res => {
      const options = res.data.map((item: Role) => ({
        label: item.name,
        value: String(item.id)
      }))
      setOptions(basicConfigList.value, 'roleIds', options)
    })
  }
  getRoleList()

  function handleEdit(id: number) {
    configType.value = 1
    http.get<User>(`admin/user/${id}`).then(res => {
      form.value = res.data
      visible.value = true
    })
  }

  function handleAdd() {
    handleClose()
    configType.value = 0
    visible.value = true
  }
  // 关闭
  function handleClose() {
    visible.value = false
    form.value = {
      username: '',
      password: '',
      status: 1,
      nickName: '',
      roleIds: []
    }
  }
  //  确认
  function handleConfirm() {
    $dialog('是否确认提交').then(() => {
      if (configType.value === 0) {
        http.post('admin/user', { ...form.value }).then(() => {
          handleClose()
          handleQuery()
          $message.success('添加成功')
        })
        return
      }
      http.put(`admin/user/${form.value.id}`, { ...form.value }).then(() => {
        handleClose()
        handleQuery()
        $message.success('修改成功')
      })
    })
  }
  const { total, list, pageNum, pageSize, handleQuery, handleDel } = useList({
    reqUrl: 'admin/user'
  })

  const { $dialog, $message } = useFastNaive()
</script>

<style scoped lang="scss">
  .role {
    padding: 16px;
    box-sizing: border-box;
  }
</style>
